/**        
 * Copyright (c) 2013 by 苏州科大国创信息技术有限公司.    
 */    
package com.github.diamond.web.controller;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.kafeitu.demo.activiti.util.PageUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.github.diamond.netty.DiamondServerHandler.ClientInfo;
import com.github.diamond.netty.DiamondServerHandler.ClientKey;
import com.github.diamond.web.service.ConfigService;
import com.github.diamond.web.service.ModuleService;
import com.github.diamond.web.service.ProjectService;

import static com.github.diamond.netty.DiamondServerHandler.*;
/**
 * Create on @2013-8-21 @下午6:55:09 
 * @author bsli@ustcinfo.com
 */
@Controller
@RequestMapping("/superdiamond")
public class ProfileController {
	@Autowired
	private ModuleService moduleService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private ProjectService projectService;
	
	private static final int LIMIT = 15;
	private static final int CLIENT_LENGTH_LIMIT = 10;
	
	@RequestMapping("/profile/{type}/{projectId}")
	public String profile(@PathVariable("type") String type, @PathVariable("projectId") Long projectId, 
			Long moduleId, ModelMap modelMap, @RequestParam(defaultValue="1")int page) {
		modelMap.addAttribute("modules", moduleService.queryModules(projectId));
		modelMap.addAttribute("configs", configService.queryConfigs(projectId, moduleId, PageUtil.getOffset(page, LIMIT), LIMIT));
		modelMap.addAttribute("moduleId", moduleId);
		modelMap.addAttribute("project", projectService.queryProject(projectId));
		
		long recordCount = configService.queryConfigCount(projectId, moduleId);
		modelMap.addAttribute("totalPages", PageUtil.pageCount(recordCount, LIMIT));
		modelMap.addAttribute("currentPage", page);
		//return "/superdiamond/profile/" + type;
		return "/superdiamond/profile/config";
	}
	
	@RequestMapping("/profile/preview/{projectCode}/{type}")
	public String preview(@PathVariable("type") String type, @PathVariable("projectCode") String projectCode, 
			Long projectId, ModelMap modelMap) {
		String config = configService.queryConfigs(projectCode, type, "");
		
		modelMap.addAttribute("project", projectService.queryProject(projectId));
		modelMap.addAttribute("message", config);
		return "/superdiamond/profile/preview";
	}
	
	@Autowired
	private  HttpServletRequest request;
	  /**
     * 查找真实的IP地址
     * 
     * @param request
     * @return
     */
    public String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    
	@RequestMapping(value="/rest/{projectCode}/{type}",produces="text/plain;charset=UTF-8")
	public @ResponseBody String rest(@PathVariable("type") String type, @PathVariable("projectCode") String projectCode, 
			String modules, ModelMap modelMap, HttpServletRequest request, HttpServletResponse resp) {
		String config;
		ClientKey key= new ClientKey();
		key.setProfile(type);
		key.setProjCode(projectCode);
		
		String format = request.getParameter("format");
		if(StringUtils.isBlank(format)) {
			format = "properties";
		}
		
		if(format.equals("json"))
			resp.setContentType("application/json;charset=UTF-8");
		else
			resp.setContentType("text/plain;charset=UTF-8");
		
		Set<ClientInfo> httpClients = ClientContoller.httpClients.get(key);
		if(httpClients==null){
			httpClients = new HashSet<ClientInfo>();
			ClientContoller.httpClients.put(key, httpClients);
		}		
		
		ClientInfo info = new ClientInfo(getRemortIP(this.request), new Date());
		synchronized(httpClients){
			if(httpClients.size() >= CLIENT_LENGTH_LIMIT){	
				httpClients.clear();				
			}
			
			httpClients.add(info);
		}
				
		if(modules!=null && modules.length()>0){
			String []moduleNames = modules.split(",");
			config = configService.queryConfigs(projectCode,moduleNames, key.getProfile(), format);		
		}
		else{
			config = configService.queryConfigs(projectCode,key.getProfile(), format);		
		}
	
		return config;
	}
	
}
